//---------------------------------------------------------------------------------
// Copyright (c) 2011, Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//---------------------------------------------------------------------------------

namespace Microsoft.Samples.ServiceBus.SilverlightChat
{
    using System;
    using System.Net;
    using System.Net.Browser;
    using System.Windows;
    using System.Windows.Threading;
    using Microsoft.Samples.ServiceBus.SilverlightChat.Models;

    public partial class App : Application
    {
        private static readonly ApplicationContext context = new ApplicationContext();
        private static Dispatcher dispatcher;

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            // In silverlight, HTTP requests can be handled through either Browser or Client HTTP
            // handling. With Browser Http Handling, only GET and POST methods are supported, response
            // headers cannot be obtained and the response body is only obtainable for 200 status 
            // codes. For more detail see: http://msdn.microsoft.com/en-us/library/dd920295(v=VS.95).aspx
            //
            // We need to use GET, POST, PUT and DELETE methods, receive response headers and access
            // the headers and response codes of requests; therefore, ClientHttp handling is required
            // The following statements set ClientHttp as the default HTTP Request handler throughout
            // the application
            bool httpResult = WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
            bool httpsResult = WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);

            InitializeComponent();
        }

        /// <summary>
        /// Gets the current Application's context
        /// </summary>
        public static ApplicationContext Context
        {
            get { return context; }
        }

        /// <summary>
        /// Get the current applications UI Thread dispatcher, used to invoke 
        /// actions on the UI.
        /// </summary>
        public static Dispatcher Dispatcher
        {
            get { return dispatcher; }
        }

        /// <summary>
        /// Helper method to display an exception in a message box.
        /// </summary>
        public static void ShowError(Exception e)
        {
            Dispatcher.BeginInvoke(() =>
            {
                MessageBox.Show("An Error Occurred:\r\n" + e.Message, "An Error Occurred", MessageBoxButton.OK);
            });
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            this.RootVisual = new MainPage();
            
            // set the dispatcher to the MainPage's dispatcher
            dispatcher = this.RootVisual.Dispatcher;
        }

        private void Application_Exit(object sender, EventArgs e)
        {
        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // If the app is running outside of the debugger then report the exception using
            // the browser's exception mechanism. On IE this will display it a yellow alert 
            // icon in the status bar and Firefox will display a script error.
            if (!System.Diagnostics.Debugger.IsAttached)
            {
                // NOTE: This will allow the application to continue running after an exception has been thrown
                // but not handled. 
                // For production applications this error handling should be replaced with something that will 
                // report the error to the website and stop the application.
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { this.ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
    }
}
